package com.msh.frame.common.util;

import com.msh.frame.client.exception.BizException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.function.Predicate;
import java.util.zip.ZipFile;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FileUtil {

  public static void mkdirParent(File file){
    File parentFile = file.getParentFile();
    if (parentFile.exists()) {
      return;
    }
    parentFile.mkdirs();
  }

  /**
   * 解压文件
   * @param t
   * @param outputPath 输出路径
   * @param fileFullNamePredicate 文件全路径匹配(入参为压缩文件内部文件的全路径)
   * @param <T>
   */
  public static <T extends ZipFile> void unZipFile(T t, String outputPath,  Predicate<String> fileFullNamePredicate){
    t.stream().forEach(z->{
      if(z.getName().endsWith("/")){
        return;
      }
      if(fileFullNamePredicate.test(z.getName())){
        File file = new File(outputPath + "/" + z.getName());
        File parentFile = file.getParentFile();
        if(!parentFile.exists()){
          parentFile.mkdirs();
        }
        try (InputStream is = t.getInputStream(z); FileOutputStream fos = new FileOutputStream(file)){
          byte[] bs = new byte[1024];
          int n = 0;
          while((n = is.read(bs)) > 0) {
            fos.write(bs, 0, n);
          }
        } catch (IOException e) {
          log.error("解压文件失败", e);
          throw new BizException("解压文件失败");
        }
      }
    });
  }
}
